﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using XYS.Core.Models;

namespace XYS.Service.Core.Filters
{
    /// <summary>
    /// 字符串格式化
    /// </summary>
    public class StringValueFilters : IActionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (GlobalCoreSetting.FormatRequestsIgnore.Any(x => Regex.IsMatch(context.HttpContext.Request.Path.Value, "^" + Regex.Escape(x).Replace("\\*", ".*") + "$"))) return;
            foreach (var argument in context.ActionArguments.Values)
            {
                FormatTrim(argument);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Do nothing
        }


        static ConcurrentDictionary<Type, List<System.Reflection.PropertyInfo>> propertiesMap = new();



        private void FormatTrim(object obj)
        {
            if (obj == null) return;
            var type = obj.GetType();
            if (!propertiesMap.TryGetValue(type, out var properties))
            {
                properties = obj.GetType().GetProperties().Where(x => x.CanWrite && x.CanRead).ToList();
                propertiesMap[type] = properties;
            }

            try
            {
                foreach (var property in properties)
                {
                    try
                    {
                        var value = property.GetValue(obj);

                        if (value != null && typeof(string) == value.GetType())
                            property.SetValue(obj, value.ToString().Trim());
                    }
                    catch { }
                }
            }
            catch { }
        }
    }
}
